#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "msg_queue.h"
#include "status.h"
#include "struct.h"
#include "tools.h"

static int msgid_ctos;
static int msgid_stoc;
Msg_ctos msg_ctos;
Msg_stoc msg_stoc;

void transf_acc(void)
{
	char acc_path[255] = {};
	char acc_path1[255] = {};

 	sprintf(acc_path,"%s%u",ACCOUNT_PATH,msg_ctos.m_acc.id);
	sprintf(acc_path1,"%s%s",ACCOUNT_PATH,msg_ctos.m_acc.name);

	Acc acc = {};
	Acc acc1 = {};



	if(ERROR == access(acc_path,F_OK))
	{
		sprintf(msg_stoc.m_str,"帐号：%d 不存在",msg_ctos.m_acc.id);
		return;
	}

	if(ERROR == access(acc_path1,F_OK))
	{
		sprintf(msg_stoc.m_str,"帐号: %s不存在",msg_ctos.m_acc.name);
		return;
	}

	int fd = open(acc_path,O_RDWR);
	int fd1 = open(acc_path1,O_RDWR);

	if(ERROR == fd)
	{
		perror("open");
		sprintf(msg_stoc.m_str,"服务器正在升级，请稍候...");
		return;
	}

	if(ERROR == fd1)
	{
		perror("open");
		sprintf(msg_stoc.m_str,"服务器正在升级，请稍后...");
		return;
	}


	if(0 >= read(fd,&acc,sizeof(acc)))
	{
		perror("read");
		sprintf(msg_stoc.m_str,"服务器正在升级，请稍候...");
		return;
	}

	if(0 >= read(fd1,&acc1,sizeof(acc1)))
	{
		perror("read");
		sprintf(msg_stoc.m_str,"请稍后...");
		return;
	}

	if(OK != strcmp(acc.pswd,msg_ctos.m_acc.pswd))
	{
		sprintf(msg_stoc.m_str,"用户或密码错误...");
		return;
	}

	if(msg_ctos.m_acc.balance > acc.balance)
	{
		sprintf(msg_stoc.m_str,"您的余额不足...");
		return;
	}
	
	acc.balance = acc.balance - msg_ctos.m_acc.balance;
	acc1.balance = acc1.balance + msg_ctos.m_acc.balance;

	lseek(fd,0,SEEK_SET);
	lseek(fd1,0,SEEK_SET);

	if(0 >= write(fd,&acc,sizeof(acc)))
	{
		perror("write");
		return;
	}

	if(0 >= write(fd1,&acc1,sizeof(acc1)))
	{
		perror("write");
		return;
	}
	close(fd);
	close(fd1);

	sprintf(msg_stoc.m_str," 余额：%g 转帐成功",acc.balance);
}

int main()
{
	msgid_ctos = get_ctos_msg();
	msgid_stoc = get_stoc_msg();

	while(true)
	{
		if(ERROR == msgrcv(msgid_ctos,&msg_ctos,sizeof(msg_ctos),M_TRANSF,0))
		{
			perror("msgrcv");
		}
		
		transf_acc();
		msg_stoc.m_type = msg_ctos.m_pid;

		if(ERROR == msgsnd(msgid_stoc,&msg_stoc,sizeof(msg_stoc.m_str),0))
		{
			perror("msgsnd");
		}
	}
}
